<template>
  <div class="modal-main" :class="{ open: open }" ref="modalMainEl">
    <div
      class="animate__animated animate__fadeInUp modal"
      ref="modalEl"
      :style="{ height: height, width: width }"
    >
      <p class="modal-title" v-if="title">{{ title }}</p>
      <div class="modal-content">
        <slot />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
interface Props {
  open: boolean
  title?: string
  height?: string
  width?: string
}

const props = withDefaults(defineProps<Props>(), {
  open: false,
  height: '200px',
  width: '85%'
})

const emit = defineEmits(['close'])

const modalMainEl = ref()
const modalEl = ref()

onMounted(() => {
  modalMainEl.value.addEventListener('click', closemodal)
})

onBeforeUnmount(() => {
  modalMainEl.value.removeEventListener('click', closemodal)
})

const closemodal = (e: any) => {
  if (!modalEl.value.contains(e.target)) {
    emit('close')
  }
}
</script>

<style scoped lang="scss">
.modal-main {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  background: #0000004d;
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 99;

  .modal {
    background: #fff;
    position: relative;
    animation-duration: 0.5s;

    .modal-title {
      height: 30px;
      line-height: 30px;
      color: #000;
      width: 100%;
      font-size: 16px;
      text-align: center;
    }

    .modal-content {
      height: 100%;
      width: 100%;
      position: relative;
      display: grid;
      place-items: center;
    }
  }
}

.open {
  display: flex;
}
</style>
